import { MutableRefObject, ReactText } from 'react';
import { extendApi, childSaveData } from '@inbiz/utils';
import type { TransferProps } from './index';
import { IFieldNames, ITree } from './components/type';

interface IParams extends TransferProps {
  treeData?: ITree[];
  onChange: (v: ReactText[]) => void;
  targetKeys: ReactText[];
  dataSource: any[];
  setState: (value: ITree[] | any[]) => void;
  fieldNames: IFieldNames;
  childModelConfig: boolean;
  selectDataRef: MutableRefObject<{}[]>;
}


export default extendApi(
  (_events: MutableRefObject<TransferProps['callBackEvents']>, params: IParams) => {
    const {
      setState,
      onChange,
      targetKeys,
      dataSource,
      fieldNames,
      treeData,
      options,
      configModalValue,
      selectDataRef,
    } = params;
    return {
      loadData: (data: ITree[] | any[]) => data && setState(data),
      setSelect: (id: ReactText, status: boolean) => {
        if (dataSource.find((item) => item[fieldNames.key] === id)) {
          onChange(
            [...new Set(targetKeys.concat(id))].filter((key) => (status ? true : key !== id)),
          );
          return true;
        } else {
          return false;
        }
      },
      getData: () => treeData ?? dataSource,
      getSaveData: () => {
        let currentIdField = configModalValue?.currentIdField || '';
        if (currentIdField.includes('$')) {
          currentIdField = currentIdField.split('$')[1];
        }
        const result = childSaveData({
          nextValue: params.value ?? [],
          options: selectDataRef?.current || dataSource || [],
          storageConfig: params.storageConfig,
          currentIdField,
        });
        return {
          value: params.targetKeys?.map((item) => item).join(','),
          childData:
            params.storageConfig && params.childModelConfig
              ? {
                  controlId: params.controlId,
                  modelKey: params.storageConfig?.business,
                  datas: result,
                }
              : undefined,
        };
      },
    };
  },
);
